package com.zhugang.week10;

/**
 * @program algorithms
 * @description: uniquePathsWithObstacles
 * @author: chanzhugang
 * @create: 2022/08/29 23:39
 */
public class UniquePathsWithObstacles {

    /**
     * 63 不同路径
     *
     * @param obstacleGrid
     * @return
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        // 计数问题： 有障碍物（1） 空位置（0）
        // dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        // 定义状态
        int[][] dp = new int[m][n];

        // 初始化第一行第一列
        if (obstacleGrid[0][0] == 1) {
            dp[0][0] = 0;
        } else {
            dp[0][0] = 1;
        }

        // 第一行初始化
        for (int i = 1; i < m; i++) {
            if (obstacleGrid[i][0] == 1) {
                dp[i][0] = 0;
            } else {
                dp[i][0] = dp[i - 1][0];
            }
        }
        // 第一列初始化
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] == 1) {
                dp[0][j] = 0;
            } else {
                dp[0][j] = dp[0][j - 1];
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else {
                    // 状态转移方程
                    dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
                }
            }
        }
        return dp[m - 1][n - 1];
    }

    public static void main(String[] args) {
        UniquePathsWithObstacles uniquePathsWithObstacles = new UniquePathsWithObstacles();
        int[][] obstacleGrid = {{1, 0}};
        int result = uniquePathsWithObstacles.uniquePathsWithObstacles(obstacleGrid);
        System.out.println(result);
    }
}